package cn.iocoder.yudao.module.eval.service.evaluator;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.eval.controller.admin.evaluator.vo.EvalEvaluatorQualificationPageReqVO;
import cn.iocoder.yudao.module.eval.controller.admin.evaluator.vo.EvalEvaluatorQualificationSaveReqVO;
import cn.iocoder.yudao.module.eval.controller.admin.evaluator.vo.EvalEvaluatorQualificationStatisticsRespVO;

import cn.iocoder.yudao.module.eval.controller.admin.evaluator.vo.EvalEvaluatorQualificationRespVO;
import cn.iocoder.yudao.module.eval.controller.admin.evaluator.vo.EvalEvaluatorQualificationBatchCreateFromUsersReqVO;
import cn.iocoder.yudao.module.eval.dal.dataobject.evaluator.EvalEvaluatorQualificationDO;
import cn.iocoder.yudao.module.eval.dal.mysql.evaluator.EvalEvaluatorQualificationMapper;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.common.util.collection.MapUtils.findAndThen;
import static cn.iocoder.yudao.module.eval.enums.ErrorCodeConstants.*;

/**
 * 考评员资质 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class EvalEvaluatorQualificationServiceImpl implements EvalEvaluatorQualificationService {

    @Resource
    private EvalEvaluatorQualificationMapper evaluatorQualificationMapper;

    @Resource
    private AdminUserApi adminUserApi;

    @Resource
    private DeptApi deptApi;

    @Override
    public Long createEvaluatorQualification(EvalEvaluatorQualificationSaveReqVO createReqVO) {
        // 验证证书编号唯一性
        validateCertificateNumberUnique(createReqVO.getCertificateNumber(), null);
        
        // 插入
        EvalEvaluatorQualificationDO evaluatorQualification = BeanUtils.toBean(createReqVO, EvalEvaluatorQualificationDO.class);
        evaluatorQualificationMapper.insert(evaluatorQualification);
        
        // 返回
        return evaluatorQualification.getId();
    }

    @Override
    public void updateEvaluatorQualification(EvalEvaluatorQualificationSaveReqVO updateReqVO) {
        // 校验存在
        validateEvaluatorQualificationExists(updateReqVO.getId());
        
        // 验证证书编号唯一性
        validateCertificateNumberUnique(updateReqVO.getCertificateNumber(), updateReqVO.getId());
        
        // 更新
        EvalEvaluatorQualificationDO updateObj = BeanUtils.toBean(updateReqVO, EvalEvaluatorQualificationDO.class);
        evaluatorQualificationMapper.updateById(updateObj);
    }

    @Override
    public void deleteEvaluatorQualification(Long id) {
        // 校验存在
        validateEvaluatorQualificationExists(id);
        
        // 删除
        evaluatorQualificationMapper.deleteById(id);
    }

    private void validateEvaluatorQualificationExists(Long id) {
        if (evaluatorQualificationMapper.selectById(id) == null) {
            throw exception(EVALUATOR_QUALIFICATION_NOT_EXISTS);
        }
    }

    private void validateCertificateNumberUnique(String certificateNumber, Long id) {
        EvalEvaluatorQualificationDO evaluatorQualification = evaluatorQualificationMapper.selectByCertificateNumber(certificateNumber);
        if (evaluatorQualification == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的资质
        if (id == null) {
            throw exception(EVALUATOR_QUALIFICATION_CERTIFICATE_DUPLICATE);
        }
        if (!evaluatorQualification.getId().equals(id)) {
            throw exception(EVALUATOR_QUALIFICATION_CERTIFICATE_DUPLICATE);
        }
    }

    @Override
    public EvalEvaluatorQualificationDO getEvaluatorQualification(Long id) {
        return evaluatorQualificationMapper.selectById(id);
    }

    @Override
    public EvalEvaluatorQualificationRespVO getEvaluatorQualificationRespVO(Long id) {
        // 获取考评员资质
        EvalEvaluatorQualificationDO qualification = evaluatorQualificationMapper.selectById(id);
        if (qualification == null) {
            return null;
        }

        // 转换为响应VO
        EvalEvaluatorQualificationRespVO respVO = BeanUtils.toBean(qualification, EvalEvaluatorQualificationRespVO.class);

        // 填充用户信息
        if (qualification.getUserId() != null) {
            AdminUserRespDTO user = adminUserApi.getUser(qualification.getUserId()).getCheckedData();
            if (user != null) {
                respVO.setUserName(user.getNickname());
                respVO.setEvaluatorName(user.getNickname());
                respVO.setEvaluatorCode("EVAL" + String.format("%06d", qualification.getUserId()));
                // respVO.setUserEmail(user.getEmail());
                respVO.setUserMobile(user.getMobile());
                // respVO.setUserGender(user.getSex());

                // 填充部门信息
                if (user.getDeptId() != null) {
                    DeptRespDTO dept = deptApi.getDept(user.getDeptId()).getCheckedData();
                    if (dept != null) {
                        respVO.setDeptName(dept.getName());
                    }
                }
            }
        }

        // 填充职业和等级信息
        respVO.setProfessionName(convertProfessionCodeToName(respVO.getProfessionCodes()));
        respVO.setQualificationLevel(convertSkillLevelsToQualificationLevel(respVO.getSkillLevels()));

        // 填充日期字段别名
        respVO.setIssueDate(respVO.getCertificateDate());
        respVO.setExpiryDate(respVO.getValidUntil());

        return respVO;
    }

    @Override
    public PageResult<EvalEvaluatorQualificationDO> getEvaluatorQualificationPage(EvalEvaluatorQualificationPageReqVO pageReqVO) {
        // 如果按考评员姓名搜索，先查询用户ID
        if (StrUtil.isNotBlank(pageReqVO.getEvaluatorName())) {
            // 根据姓名查询用户
            // List<AdminUserRespDTO> users = adminUserApi.getUserListByNickname(pageReqVO.getEvaluatorName()).getCheckedData();
            List<AdminUserRespDTO> users = new ArrayList<>(); // 临时解决方案
            if (CollUtil.isEmpty(users)) {
                // 没有找到匹配的用户，返回空结果
                return PageResult.empty();
            }

            // 获取用户ID列表
            Set<Long> userIds = convertSet(users, AdminUserRespDTO::getId);

            // 如果同时指定了userId，取交集
            if (pageReqVO.getUserId() != null) {
                if (!userIds.contains(pageReqVO.getUserId())) {
                    return PageResult.empty();
                }
                userIds = Set.of(pageReqVO.getUserId());
            }

            // 分页查询考评员资质
            return evaluatorQualificationMapper.selectPageByUserIds(pageReqVO, userIds);
        }

        return evaluatorQualificationMapper.selectPage(pageReqVO);
    }

    @Override
    public List<EvalEvaluatorQualificationDO> getEvaluatorQualificationList(EvalEvaluatorQualificationPageReqVO exportReqVO) {
        return evaluatorQualificationMapper.selectList(exportReqVO);
    }

    @Override
    public EvalEvaluatorQualificationDO getEvaluatorQualificationByUserId(Long userId) {
        return evaluatorQualificationMapper.selectByUserId(userId);
    }

    @Override
    public List<EvalEvaluatorQualificationDO> getEvaluatorQualificationListByUserIds(Collection<Long> userIds) {
        return evaluatorQualificationMapper.selectListByUserIds(userIds);
    }

    @Override
    public EvalEvaluatorQualificationDO getEvaluatorQualificationByCertificateNumber(String certificateNumber) {
        return evaluatorQualificationMapper.selectByCertificateNumber(certificateNumber);
    }

    @Override
    public void renewEvaluatorQualification(Long id, String validUntil) {
        // 校验存在
        validateEvaluatorQualificationExists(id);
        
        // 更新有效期
        EvalEvaluatorQualificationDO updateObj = new EvalEvaluatorQualificationDO();
        updateObj.setId(id);
        updateObj.setValidUntil(LocalDate.parse(validUntil));
        updateObj.setQualificationStatus(1); // 设置为有效
        evaluatorQualificationMapper.updateById(updateObj);
    }

    @Override
    public void suspendEvaluatorQualification(Long id) {
        // 校验存在
        validateEvaluatorQualificationExists(id);
        
        // 暂停资质
        EvalEvaluatorQualificationDO updateObj = new EvalEvaluatorQualificationDO();
        updateObj.setId(id);
        updateObj.setQualificationStatus(2); // 设置为暂停
        evaluatorQualificationMapper.updateById(updateObj);
    }

    @Override
    public void resumeEvaluatorQualification(Long id) {
        // 校验存在
        validateEvaluatorQualificationExists(id);

        // 恢复资质
        EvalEvaluatorQualificationDO updateObj = new EvalEvaluatorQualificationDO();
        updateObj.setId(id);
        updateObj.setQualificationStatus(1); // 设置为有效
        evaluatorQualificationMapper.updateById(updateObj);
    }

    @Override
    public void enableEvaluatorQualification(Long id) {
        // 校验存在
        validateEvaluatorQualificationExists(id);

        // 启用资质
        EvalEvaluatorQualificationDO updateObj = new EvalEvaluatorQualificationDO();
        updateObj.setId(id);
        updateObj.setQualificationStatus(1); // 设置为有效
        evaluatorQualificationMapper.updateById(updateObj);
    }

    @Override
    public void disableEvaluatorQualification(Long id) {
        // 校验存在
        validateEvaluatorQualificationExists(id);

        // 禁用资质
        EvalEvaluatorQualificationDO updateObj = new EvalEvaluatorQualificationDO();
        updateObj.setId(id);
        updateObj.setQualificationStatus(0); // 设置为无效
        evaluatorQualificationMapper.updateById(updateObj);
    }

    @Override
    public EvalEvaluatorQualificationStatisticsRespVO getEvaluatorQualificationStatistics() {
        EvalEvaluatorQualificationStatisticsRespVO statistics = new EvalEvaluatorQualificationStatisticsRespVO();

        // 总考评员数
        statistics.setTotalCount(evaluatorQualificationMapper.selectCount());

        // 有效资质数（状态为1）
        statistics.setValidCount(evaluatorQualificationMapper.selectCountByQualificationStatus(1));

        // 即将过期数（30天内过期的有效资质）
        LocalDate today = LocalDate.now();
        LocalDate thirtyDaysLater = today.plusDays(30);
        statistics.setExpiringSoonCount(evaluatorQualificationMapper.selectCountByValidUntilBetween(today, thirtyDaysLater));

        // 已过期数（有效期在今天之前的）
        statistics.setExpiredCount(evaluatorQualificationMapper.selectCountByValidUntilBefore(today));

        return statistics;
    }

    @Override
    public Integer batchCreateEvaluatorQualificationFromUsers(EvalEvaluatorQualificationBatchCreateFromUsersReqVO batchCreateReqVO) {
        log.info("[batchCreateEvaluatorQualificationFromUsers] 开始批量创建考评员资质，用户数量：{}", batchCreateReqVO.getUserIds().size());

        int successCount = 0;

        for (Long userId : batchCreateReqVO.getUserIds()) {
            try {
                // 检查用户是否已经是考评员
                EvalEvaluatorQualificationDO existingQualification = evaluatorQualificationMapper.selectByUserId(userId);
                if (existingQualification != null) {
                    log.warn("[batchCreateEvaluatorQualificationFromUsers] 用户{}已经是考评员，跳过", userId);
                    continue;
                }

                // 创建考评员资质
                EvalEvaluatorQualificationDO qualification = new EvalEvaluatorQualificationDO();
                qualification.setUserId(userId);

                // 设置职业代码，如果没有提供则使用默认值
                qualification.setProfessionCodes(StrUtil.isNotBlank(batchCreateReqVO.getProfessionCodes())
                    ? batchCreateReqVO.getProfessionCodes()
                    : "6-31-01-06"); // 默认软件设计师

                // 设置技能等级，如果没有提供则使用默认值
                qualification.setSkillLevels(StrUtil.isNotBlank(batchCreateReqVO.getSkillLevels())
                    ? batchCreateReqVO.getSkillLevels()
                    : "五级,四级,三级");

                // 生成唯一证书编号
                qualification.setCertificateNumber(generateCertificateNumber("USER" + userId));

                // 设置发证机构
                qualification.setCertificateIssuer(StrUtil.isNotBlank(batchCreateReqVO.getCertificateIssuer())
                    ? batchCreateReqVO.getCertificateIssuer()
                    : "广东省人力资源和社会保障厅");

                // 设置发证日期
                qualification.setCertificateDate(batchCreateReqVO.getCertificateDate() != null
                    ? batchCreateReqVO.getCertificateDate()
                    : LocalDate.now());

                // 设置有效期
                qualification.setValidUntil(batchCreateReqVO.getValidUntil() != null
                    ? batchCreateReqVO.getValidUntil()
                    : LocalDate.now().plusYears(3));

                // 设置专业领域
                qualification.setSpecialties(StrUtil.isNotBlank(batchCreateReqVO.getSpecialties())
                    ? batchCreateReqVO.getSpecialties()
                    : "通用技能");

                // 设置最大工作负荷
                qualification.setMaxWorkload(batchCreateReqVO.getMaxWorkload() != null
                    ? batchCreateReqVO.getMaxWorkload()
                    : 15);

                // 设置资质状态
                qualification.setQualificationStatus(batchCreateReqVO.getQualificationStatus());

                // 插入数据库
                evaluatorQualificationMapper.insert(qualification);
                successCount++;

                log.info("[batchCreateEvaluatorQualificationFromUsers] 成功为用户{}创建考评员资质", userId);

            } catch (Exception e) {
                log.error("[batchCreateEvaluatorQualificationFromUsers] 为用户{}创建考评员资质失败", userId, e);
            }
        }

        log.info("[batchCreateEvaluatorQualificationFromUsers] 批量创建完成，成功数量：{}", successCount);
        return successCount;
    }

    /**
     * 生成证书编号
     */
    private String generateCertificateNumber(String userCode) {
        String timestamp = String.valueOf(System.currentTimeMillis()).substring(8);
        return "EVAL" + LocalDate.now().getYear() + timestamp;
    }

    /**
     * 将职业代码转换为职业名称
     */
    private String convertProfessionCodeToName(String professionCodes) {
        if (StrUtil.isBlank(professionCodes)) {
            return "";
        }

        // 简单的代码到名称映射，实际应用中可以从数据字典获取
        String firstCode = professionCodes.split(",")[0].trim();
        switch (firstCode) {
            case "6-31-01-06":
                return "软件设计师";
            case "6-31-01-03":
                return "电工";
            case "6-31-01-04":
                return "机械维修工";
            case "6-31-01-05":
                return "焊工";
            default:
                return "通用技能";
        }
    }

    /**
     * 将技能等级转换为资质等级
     */
    private String convertSkillLevelsToQualificationLevel(String skillLevels) {
        if (StrUtil.isBlank(skillLevels)) {
            return "";
        }

        // 根据技能等级确定资质等级
        if (skillLevels.contains("一级")) {
            return "高级技师";
        } else if (skillLevels.contains("二级")) {
            return "技师";
        } else if (skillLevels.contains("三级")) {
            return "高级工";
        } else if (skillLevels.contains("四级")) {
            return "中级工";
        } else if (skillLevels.contains("五级")) {
            return "初级工";
        } else {
            return "通用";
        }
    }

    @Override
    public PageResult<EvalEvaluatorQualificationRespVO> buildEvaluatorQualificationRespVOPage(PageResult<EvalEvaluatorQualificationDO> pageResult) {
        if (pageResult == null || pageResult.getList().isEmpty()) {
            return PageResult.empty();
        }

        List<EvalEvaluatorQualificationDO> qualifications = pageResult.getList();

        // 获取所有用户ID
        Set<Long> userIds = convertSet(qualifications, EvalEvaluatorQualificationDO::getUserId);

        // 批量查询用户信息（使用API）
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(userIds);

        // 批量查询部门信息
        Set<Long> deptIds = convertSet(userMap.values(), AdminUserRespDTO::getDeptId);
        Map<Long, DeptRespDTO> deptMap = deptApi.getDeptMap(deptIds);

        // 转换为响应VO并填充用户信息
        List<EvalEvaluatorQualificationRespVO> respVOList = BeanUtils.toBean(qualifications, EvalEvaluatorQualificationRespVO.class);

        respVOList.forEach(respVO -> {
            // 填充用户信息
            findAndThen(userMap, respVO.getUserId(), user -> {
                respVO.setUserName(user.getNickname());
                respVO.setEvaluatorName(user.getNickname()); // 考评员姓名与用户姓名相同
                respVO.setEvaluatorCode("EVAL" + String.format("%06d", respVO.getUserId())); // 生成考评员编码
                respVO.setUserMobile(user.getMobile());
                // respVO.setUserEmail(user.getEmail());
                // respVO.setUserGender(user.getSex());

                // 填充部门信息
                findAndThen(deptMap, user.getDeptId(), dept -> {
                    respVO.setDeptName(dept.getName());
                });
            });

            // 填充职业和等级信息
            respVO.setProfessionName(convertProfessionCodeToName(respVO.getProfessionCodes()));
            respVO.setQualificationLevel(convertSkillLevelsToQualificationLevel(respVO.getSkillLevels()));

            // 填充日期字段别名
            respVO.setIssueDate(respVO.getCertificateDate());
            respVO.setExpiryDate(respVO.getValidUntil());
        });

        return new PageResult<>(respVOList, pageResult.getTotal());
    }

    @Override
    public List<EvalEvaluatorQualificationRespVO> getEvaluatorListByStatus(Integer qualificationStatus) {
        // 查询指定状态的考评员资质
        List<EvalEvaluatorQualificationDO> qualifications = evaluatorQualificationMapper.selectListByQualificationStatus(qualificationStatus);

        if (CollUtil.isEmpty(qualifications)) {
            return List.of();
        }

        // 获取所有用户ID
        Set<Long> userIds = convertSet(qualifications, EvalEvaluatorQualificationDO::getUserId);

        // 批量查询用户信息
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(userIds);

        // 转换为响应VO并填充用户信息
        List<EvalEvaluatorQualificationRespVO> respVOList = BeanUtils.toBean(qualifications, EvalEvaluatorQualificationRespVO.class);

        respVOList.forEach(respVO -> {
            // 填充用户信息
            findAndThen(userMap, respVO.getUserId(), user -> {
                respVO.setUserName(user.getNickname());
                respVO.setEvaluatorName(user.getNickname()); // 考评员姓名与用户姓名相同
                respVO.setEvaluatorCode("EVAL" + String.format("%06d", respVO.getUserId())); // 生成考评员编码
                respVO.setUserMobile(user.getMobile());
                // respVO.setUserEmail(user.getEmail());
                // respVO.setUserGender(user.getSex());
            });

            // 填充职业和等级信息
            respVO.setProfessionName(convertProfessionCodeToName(respVO.getProfessionCodes()));
            respVO.setQualificationLevel(convertSkillLevelsToQualificationLevel(respVO.getSkillLevels()));

            // 填充日期字段别名
            respVO.setIssueDate(respVO.getCertificateDate());
            respVO.setExpiryDate(respVO.getValidUntil());
        });

        return respVOList;
    }

}